/*
 * WapLoginInterceptor.java
 * Copyright 2021 Qunhe Tech, all rights reserved.
 * Qunhe PROPRIETARY/CONFIDENTIAL, any form of usage is subject to approval.
 */

package top.bbman.boot.auth.interceptor;

import cn.hutool.core.util.StrUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import top.bbman.boot.auth.component.AESComponent;
import top.bbman.boot.auth.component.LoginComponent;
import top.bbman.boot.auth.utils.CookieUtil;
import top.bbman.boot.auth.utils.RequestAttrUtil;
import top.bbman.boot.auth.vo.UserCookie;
import top.bbman.boot.logger.LogConstant;
import top.bbman.boot.repository.constant.PeaBeanName;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 描述:
 *
 * @author wangbei
 */
@Component
public class WapLoginInterceptor extends TrackableInterceptor {

    @Resource(name = PeaBeanName.Auth.LOGIN)
    private LoginComponent loginComponent;

    @Resource(name = PeaBeanName.Auth.AES)
    private AESComponent aesComponent;

    @Value("${bb-man.auth.head-token-name}")
    private String headTokenName;

    @Override
    public boolean doPreHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!isAfterInterceptor(request, PreLoginInterceptor.class)) {
            LogConstant.bbManAuth.error("必须先配置以下拦截器 {} on {}", PreLoginInterceptor.class.getName(), request.getRequestURI());
        }

        // 获取token
        List<UserCookie> userCookies = this.toUserCookies(request);
        String token = this.getToken(userCookies);
        LogConstant.bbManAuth.info("head token: {}", token);

        if(StrUtil.isNotBlank(token)) {
            String userId = loginComponent.findIdByToken(token);
            if(StrUtil.isNotBlank(userId)) {
                RequestAttrUtil.setUserIdFromRequest(userId);
                RequestAttrUtil.setTokenFromRequest(aesComponent.decrypt(token));
                LogConstant.bbManAuth.info("token correspond userId: {}", userId);
//                CookieUtil.applyUserCookies(response, userCookies);
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView){

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex){

    }

    public List<UserCookie> toUserCookies(HttpServletRequest request) {
        List<UserCookie> userCookies = new ArrayList<>();
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                UserCookie userCookie = new UserCookie();
                userCookie.setName(cookie.getName());
                userCookie.setValue(cookie.getValue());
                userCookie.setMaxAge(3600 * 24 * 7);
                userCookies.add(userCookie);
            }
        }
        String token = request.getHeader(headTokenName);
        if(StringUtils.isNotEmpty(token)){
            UserCookie userCookie = new UserCookie();
            userCookie.setName(headTokenName);
            userCookie.setValue(token);
            userCookies.add(userCookie);
        }
        return userCookies;
    }

    public String getToken(List<UserCookie> userCookieList) {
        for (UserCookie userCookie : userCookieList) {
            if(userCookie.getName().equals(headTokenName)) {
                return userCookie.getValue();
            }
        }

        return null;
    }
}

